<?php
declare (strict_types=1);

namespace app\common\model\customer;

use app\common\model\Region;
use cores\BaseModel;
use think\model\relation\BelongsTo;

/**
 * 客户模型
 * Class Customer
 * @package app\common\model
 */
class Customer extends BaseModel
{
    // 定义主键
    protected $pk = 'customer_id';


    protected $append = [
        'region_text',
    ];

    public function getRegionAttr($value, $data)
    {
        return $this->getRegionIds($data['region']);
    }

    public function getRegionIds($value)
    {
        return !empty($value) ? array_map('intval', explode(',', $value)) : [];
    }

    /**
     * 关联销售记录表
     * @return BelongsTo
     */
    public function storeUser(): BelongsTo
    {
        $module = self::getCalledModule();
        return $this->belongsTo("app\\{$module}\\model\\store\\User", 'store_user_id');
    }

    /**
     * 省市区名称集
     * @param $value
     * @param $data
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getRegionTextAttr($value, $data)
    {
        $region = $this->getRegionIds($data['region']);
        if (!empty($region) && count($region) == 3) {
            return $this->getRegionNames($region);
        }
        return '';
    }

    /**
     * 获取完整地址
     * @param $value
     * @param $data
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getFullAddressAttr($value, $data): string
    {
        $rgionNames = $this->getRegionNames($data);
        return "{$rgionNames['province']}{$rgionNames['city']}{$rgionNames['region']}{$data['detail']}";
    }

    /**
     * 获取省市区名称
     * @param array $data
     * @return array|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    private function getRegionNames(array $data)
    {
        $dataset = [Region::getNameById($data[0]), Region::getNameById($data[1]), Region::getNameById($data[2]),];
        return implode(' / ', $dataset);
    }

    /**
     * 关联来源记录表
     * @return BelongsTo
     */
    public function source(): BelongsTo
    {
        $module = self::getCalledModule();
        return $this->belongsTo("app\\{$module}\\model\\presalesCustomer\\Source", 'pcs_id');
    }
}
